package com.leizhi.demo.monitor.achieve.listener;

import com.leizhi.demo.monitor.achieve.SipService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sip.*;
import javax.sip.header.CSeqHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;

/**
 * @Description SIP 监听点
 * @Version 1.0.0-SNAPSHOT
 * @Author leizhi
 * @Date 2025/4/27 11:58
 */
public class SipListenerPoint implements SipListener {

    private static final Logger logger = LoggerFactory.getLogger(SipListenerPoint.class);

    private final SipService sipService;


    public SipListenerPoint(SipService sipService) {
        this.sipService = sipService;
    }

    @Override
    public void processRequest(RequestEvent requestEvent) {
        Request request = requestEvent.getRequest();
        String method = request.getMethod();
        try {
            if (method.equalsIgnoreCase(Request.REGISTER)) {
                sipService.processRegister(requestEvent, getTransport(request));
            } else if (method.equalsIgnoreCase(Request.MESSAGE)) {
                sipService.processMessage(requestEvent, getTransport(request));
            } else if (method.equalsIgnoreCase(Request.BYE)) {
                sipService.processBye(requestEvent, getTransport(request));
            }
        } catch (Exception e) {
            logger.error("processRequest error >>> {}", e.getMessage());
        }
    }

    @Override
    public void processResponse(ResponseEvent responseEvent) {
        Response response = responseEvent.getResponse();
        CSeqHeader cseqHeader = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
        String method = cseqHeader.getMethod();
        try {
            if (Request.INVITE.equals(method)) {
                int statusCode = response.getStatusCode();
                if (statusCode == Response.OK) {
                    sipService.processAck(responseEvent);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }

    @Override
    public void processTimeout(TimeoutEvent timeoutEvent) {

    }

    @Override
    public void processIOException(IOExceptionEvent ioExceptionEvent) {

    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {

    }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {

    }

    /* 获取请求协议类型 */
    private String getTransport(Request request) {
        ViaHeader header = (ViaHeader) request.getHeader(ViaHeader.NAME);
        return header.getTransport();
    }

}
